﻿/*
Create by: Nguyen Thai Thinh
Create date: 10/7/2012
Tracking Core: Duoc viet theo mo hinh 3 lop Interface-Business-Data(Processor)
*/

var timeIntervalRefreshGrid;
var timeRefresDevice;
var TIMEOUTSOS;
var titleTab = "";
var flagAddTab = true;
var VEHICLEOBJ = 2;
var MKROUTER = 10;
var LINEROUTER = 11;
var flagAddPositionInputInfo = false;
var flagUpdateNhapThongTin = false;
var flagAdd_EditNguoiDung = false;
var typeReport = 1; //Loai report
var delta; // chieu cao header cua  report
//bien toa cuc khoi tao cho ngay thang nam
var fromdate = "";
var todate = "";

var deviceidSelect = "";
//Trang thai xe(trang thai GPS)
var nRed = 1;
var nBlue = 1;
var nYellow = 1;
var nGray = 1;
var nNumRed = 0;
var nNumBlue = 0;
var nNumYellow = 0;
var nNumGrey = 0;
//Khai bao phan Xem lai lo trinh
var arrMarkerRouter = new Array();
var arrPath = new Array();
var arrLine = new Array();
var markerSelectet = 0;
//Bien active window: dung de kiem tra co window nao dang active hay k
var bActiveWindow = false;
var fSearchDevice = false;
var nIconW = 32;
var nIconH = 32;
var nLng = 0;
var nBuleClick = 0;
var nRedClick = 0;
var nYellowClick = 0;
var nGrayClick = 0;
var nOffsetTop = 45;
var nOffsetLeft = 45;
var nDisplay = 0;
var SELECT_TAB = 0;
var nTimeInterValGrid = 7000;
var nTimeInterValDevice = 5000;
var nAlertSpeed = 0;

if (typeof Tracking == 'undefined')
    Tracking = {};
Tracking.Core = {
    Init: {
        Onload: function () {
            $(function () {
                //Call Function after loadmap()
                //Tracking.Core.Init.OnResize();
                Tracking.Core.Processor.GetDisplayMarker();
                // Tracking.Core.Init.LoadTab(); //Do danh sach thiet bi la load mac dinh nen no duoc load len trong lan chay dau tien
                Tracking.Core.Init.GetInfoCompany();
                Tracking.Core.Init.GetUserOnline();
                //Tracking.Core.Init.VehicleStatus();
                Tracking.Core.Interface.SelectecMenu();
                Tracking.Core.Init.GetDevices();
                //Goi ham setInterval: la chay theo chu ky thoi gian da dinh. SettimeOut: chi chay delay sau 1 khoan thoi gian da dinh(chay 1 lan neu chi goi 1 lan); 
                timeRefresDevice = setInterval('Tracking.Core.Processor.RefreshDevice();', nTimeInterValDevice);
                timeIntervalRefreshGrid = setInterval('Tracking.Core.Processor.RefreshDataForGrid();', nTimeInterValGrid); //Set 

                // TIMEOUTSOS = setInterval('Tracking.Core.Init.ShowSOS();', 7000);
                if (dsTrackingMyMap == null) {
                    dsTrackingMyMap = new Object();
                    dsTrackingMyMap.Tables = new Array();
                    dsTrackingMyMap.Tables[0] = new Object();
                    dsTrackingMyMap.Tables[0].Rows = new Array();
                }
            });

            //showtime();
        },  //the End Function Onload
        OnResize: function () {
            $(function () {
                $("#main").css({ 'width': $(window).width() - 1, 'height': $(window).height() - $('#divOnTop').height() - 3 });
                $('#main').layout('panel', 'south').panel({
                    onCollapse: function () {
                        $('#main').layout();
                        map.checkResize();

                    },
                    onExpand: function () {
                        $('#main').layout();
                        map.checkResize();

                    }
                });

                $('#main').layout('panel', 'west').panel({
                    onCollapse: function () {
                        $('#main').layout();
                        map.checkResize();

                    },
                    onExpand: function () {
                        $('#main').layout();
                        map.checkResize();
                    }
                });

            });
            if (map != null) {
                $('#main').layout();
                map.checkResize();
            }
            else {
                $('#main').layout();
            }

        },

        LoadDataToGrid: function (keySearch) {
            $(function () {
                $('#tbDanhSachThietBi').datagrid({
                    method: 'get',
                    singleSelect: true,
                    url: 'service/getdata.ashx',
                    pagination: true,
                    rownumbers: true,
                    nowrap: false,
                    fitColumns: true,
                    showPageList: false,
                    pageSize: 10,
                    pageList: [10, 20, 30],
                    idField: 'TrackID',
                    cache: false,
                    loadMsg: '',
                    queryParams: { keysearch: keySearch },
                    onLoadError: function (error) {
                        window.location.href = "Login.aspx";
                        //$.messager.alert('Thông báo!', 'Load dữ liệu bị lỗi!', 'error');
                        Tracking.Core.Processor.ClearTimeOut();
                        return;
                    },
                    onLoadSuccess: function (data) {
                        if (deviceidSelect != '') {
                            $('#tbDanhSachThietBi').datagrid('selectRecord', deviceidSelect);
                        }
                        if (!bActiveWindow) {
                            $('#txtSearchDevice').focus();
                        }
                        if (fSearchDevice) {
                            Tracking.Core.Business.DisplayResultSearch($('#tbDanhSachThietBi').datagrid('getData').total, keySearch);
                        }
                        if (markerSelectet == 0)
                            Tracking.Core.Interface.UnSelectRecord('tbDanhSachThietBi');

                    },
                    onClickRow: function (id, ob) {
                        Tracking.Core.Processor.ClearAllVehicleMk();
                        Tracking.Core.Processor.GetDeviceDetailByTrackID(ob.TrackID);

                        deviceidSelect = '';
                    },
                    onDblClickRow: function (id, ob) {

                    }
                });
            });
        },


        XemLoTrinh: function (fdate, tdate, selectSearch, SelectTypeSearch, deviceid) {
            $(function () {
                $('#tbXemlailotrinh').datagrid({
                    singleSelect: true,
                    method: 'get',
                    url: 'service/xemlotrinh.ashx',
                    fitColumns: true,
                    nowrap: false,
                    pagination: true,
                    rownumbers: true,
                    pageSize: 50,
                    pageList: [100, 150, 200],
                    idField: 'ID',
                    loadMsg: '',
                    // view: bufferview,
                    queryParams: { 'fdate': fdate, 'tdate': tdate, 'selectSearch': selectSearch, 'SelectTypeSearch': SelectTypeSearch, deviceid: deviceid },
                    onLoadError: function () {
                        return;
                    },
                    onLoadSuccess: function () {

                        //$('#tbXemlailotrinh').datagrid('selectRecord', '281479271678063');
                    },
                    onClickRow: function (id, ob) {

                        /*  if (arrVehicleMk.lengt > 0) {
                        map.removeOverlay(arrVehicleMk[0]);
                        }

                        arrVehicleMk = new Array();
                        var obj = new Object();
                        obj.Latidue = ob.Latidue;
                        obj.Longtitude = ob.Longtitude;
                        obj.ID = ob.ID;
                        obj.index = 0;
                        obj.GPS = 'A';
                        Tracking.Core.Interface.CreateNewOneMarkerDevice(obj, obj.index);
                        Tracking.Core.Interface.ShowVehicleWindow(ob.TrackID, obj.index, ob.ID);
                        //Latidue: Y, Longtitude: X
                        map.setCenter(new VLatLng(parseFloat(ob.Latidue - 10), parseFloat(ob.Longtitude)), map.getLevel());
                        */
                    }
                });
            });
        },

        //Tao grid
        QuanLyTinNhan: function () {
            $(function () {
                $('#tbQuanLyTinNhan').datagrid({
                    method: 'get',
                    singleSelect: true,
                    url: 'service/QuanLyTinNhan.ashx', //Goi len Server de get du lieu
                    pagination: true,
                    rownumbers: true,
                    nowrap: false,
                    fitColumns: true,
                    showPageList: false,
                    pageSize: 50,
                    queryParams: {},
                    onLoadError: function () {
                        return;
                    },
                    onLoadSuccess: function () {


                    },
                    onClickRow: function (id, ob) {

                    }
                });
            });
        },

        //Tao grid
        QuanLyThuDienTu: function () {
            $(function () {
                $('#tbQuanLyThuDienTu').datagrid({
                    method: 'get',
                    singleSelect: true,
                    url: 'service/QuanLyThuDienTu.ashx', //Goi len Server de get du lieu
                    pagination: true,
                    rownumbers: true,
                    nowrap: false,
                    fitColumns: true,
                    showPageList: false,
                    pageSize: 50,
                    queryParams: {},
                    onLoadError: function () {
                        return;
                    },
                    onLoadSuccess: function () {


                    },
                    onClickRow: function (id, ob) {

                    }
                });
            });
        },

        //Tao grid
        DanhSachVung: function () {
            $(function () {
                $('#tbDanhSachVung').datagrid({
                    method: 'get',
                    singleSelect: true,
                    url: 'service/DanhSachVung.ashx',
                    pagination: true,
                    rownumbers: true,
                    nowrap: false,
                    fitColumns: true,
                    showPageList: false,
                    pageSize: 50,
                    queryParams: {},
                    onLoadError: function () {
                        return;
                    },
                    onLoadSuccess: function () {


                    },
                    onClickRow: function (id, ob) {

                    },
                    onRowContextMenu: function (e, rowindex, rowData) {
                        $('#tbDanhSachVung').datagrid('selectRow', rowindex);
                        $('#divDanhSachVung').bind('contextmenu', function () {
                            $('#popdanhsachvung').menu('show', {
                                left: e.pageX,
                                top: e.pageY
                            });
                            return false;
                        });
                    },
                    onHeadContextMenu: function (e) {
                        return false;
                    }
                });
            });
        },

        //Tao grid
        NhapThongTin: function () {

            $('#tbNhapThongTin').datagrid({
                method: 'get',
                singleSelect: true,
                url: 'service/NhapThongTin.ashx', //Goi len Server de get du lieu
                pagination: true,
                rownumbers: true,
                nowrap: false,
                fitColumns: true,
                showPageList: false,
                pageSize: 50,
                queryParams: {},
                onLoadError: function () {
                    return;
                },
                onLoadSuccess: function () {


                },
                onClickRow: function (id, ob) {

                },
                onDblClickRow: function (rowindex, rowdata) {
                    flagUpdateNhapThongTin = true;
                    flagAddPositionInputInfo = true;
                    Tracking.Core.Business.UpdateNhapThongTin(rowdata, rowindex);

                }
            });


            var pager = $('#tbNhapThongTin').datagrid('getPager'); // get the pager of datagrid
            pager.pagination({
                buttons: [{
                    iconCls: 'icon-add',
                    handler: function () {
                        flagAddPositionInputInfo = true;
                        Tracking.Core.Processor.OpenWindow(1, 'PropertyNhapThongTin.aspx', 'quanly', 'Nhập thông tin', 320, 270, false, false, false, false, true, false, true);
                        $('#btnNhapThongTin').html('<span class="l-btn-left"><span class="l-btn-text icon-ok" style="padding-left: 20px;">Thêm mới</span></span>')
                        $('#btnNhapThongTin').die();
                        $('#btnNhapThongTin').live('click', function () { Tracking.Core.Business.NhapThongTin(1) });

                    }
                },
                {
                    iconCls: 'icon-remove',
                    handler: function () {
                        Tracking.Core.Business.DeleteNhapThongTin();
                    }
                },
                {
                    iconCls: 'icon-edit',
                    handler: function () {
                        flagUpdateNhapThongTin = true;
                        flagAddPositionInputInfo = true;
                        var rowdata = $('#tbNhapThongTin').datagrid('getSelected');
                        if (rowdata == null) {
                            $.messager.alert('Thông báo!', 'Vui lòng chọn dòng cần cập nhật!', 'info');
                            return;
                        }
                        else {
                            var index = $('#tbNhapThongTin').datagrid('getRowIndex', rowdata);
                            Tracking.Core.Business.UpdateNhapThongTin(rowdata, index);
                        }
                    }
                }]
            });

        },

        // Ham nay get ve danh dach cac thiet bi theo khung view. Du lieu tra ve dang JSON
        GetDevices: function () {
            nNumRed = 0;
            nNumBlue = 0;
            nNumYellow = 0;
            nNumGrey = 0;
            var obj = new Object();
            obj = Tracking.Core.Business.GetBoundRect();
            var nDisplayWidth = $(window).width();
            var nDisplayHeight = $(window).height();
            var nIconWidth = nIconW;
            var nIconHeight = nIconH;
            var arrTrkID = new Array();
            if (objDevices != null) {
                for (var i = 0; i < objDevices.length; i++) {
                    arrTrkID[i] = objDevices[i].ID;
                }

            }
            var param = "param={dMinLat:'" + parseFloat(obj.dMinLat) + "',dMinLng:'" + parseFloat(obj.dMinLng) + "',dMaxLat:'" + parseFloat(obj.dMaxLat) + "',dMaxLng:'" + parseFloat(obj.dMaxLng) + "',nDisplayWidth:'" + nDisplayWidth + "',nDisplayHeight:'" + nDisplayHeight + "',nIconWidth:'" + nIconWidth + "', nIconHeight:'" + nIconHeight + "',arrTrk:'" + arrTrkID + "' }";
            Tracking.Core.Ajax.CallServer('Service/GetDevices.ashx', param, Tracking.Core.Interface.CreateMarkerDevice, 'GET', 'true', '', '');

        },

        LoadTab: function () {
            try {
                Tracking.Core.Interface.CreateTab('tab', 'Danh sách thiết bị', 'DanhSachThietBi.aspx', '', 'icon-devices', false, true, 1);
                Tracking.Core.Interface.CreateTab('tab', 'Xem lại lộ trình', 'XemLaiLoTrinh.aspx', 'Xem lại lộ trình', 'icon-history', true, false, 'xemlailotrinh');
                //            Tracking.Core.Interface.CreateTab('tab', 'Danh sách vùng', 'DanhSachVung.aspx', 'Danh sach vung', 'icon-zones', true, false, 'Danhsachvung');
                //            Tracking.Core.Interface.CreateTab('tab', 'Kết quả tìm đường', '', 'Ket qua tim duong', 'icon-timduong', true, false, 'Ketquatimduong');
                //            Tracking.Core.Interface.CreateTab('tab', 'Kết quả tìm nhóm thiết bị', '', 'Ket qua tim nhom thiet bi', 'icon-find', true, false, 'kqtimnhothietbi');
                //            Tracking.Core.Interface.CreateTab('tab', 'Quản lý thư điện tử', 'QuanLyThuDienTu.aspx', '', 'icon-Mail', true, false, 'qlthudientu');
                //            Tracking.Core.Interface.CreateTab('tab', 'Quản lý tin nhắn', 'QuanLyTinNhan.aspx', '', 'icon-Message', true, false, 'qltinnhan');
                //            Tracking.Core.Interface.CreateTab('tab', 'Nhập thông tin', 'NhapThongTin.aspx', '', 'icon-edit', true, false, 'nhapthongtin');
                Tracking.Core.Init.InitDate();
                Tracking.Core.Processor.BindEventForTab();
            } catch (e) {

            }

        },
        InitDate: function () {
            var d = new Date();
            var day = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
            fromdate = day + ' 00:00:00';
            todate = day + ' 23:59:59';
        },
        GetInfoCompany: function () {
            var hostname = location.hostname;
            var pData = "{ param:\"{hostname:'" + hostname + "'}\"}";
            Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/GetCompanyInfo', pData, Tracking.Core.Processor.GetInfoCompanyCallBack, 'POST', 'true', 'json', 'application/json; charset=utf-8');

        },
        GetUserOnline: function () {
            Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/CoutUserOnline', '', Tracking.Core.Interface.NumUserOnline, 'POST', 'true', 'json', 'application/json; charset=utf-8');
        },
        VehicleStatus: function () {
            Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/CountVehicleStatus', '', Tracking.Core.Interface.VehicleStatus, 'POST', 'true', 'json', 'application/json; charset=utf-8');
        },
        GetUserNameAndPassword: function () {
            var sUaP = Tracking.Core.Browser.getCookie('thaithinh');
            var param = sUaP;
            if (sUaP != '') {
                Tracking.Core.Ajax.CallServer('Service/Utilities/GetUerAndPassWord.ashx', param, Tracking.Core.Processor.GetUserNameAndPasswordCallback, 'GET', true, 'json', '');
            }
            else {

                $('#txtUserName').focus();
            }
        },
        ShowSOS: function () {
            Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/CheckSOS', '', Tracking.Core.Processor.ShowSOS, 'GET', true, 'json', '');

        }
    }, //End Init

    Processor: {
        SetDisplayTextForTable: function (divContent, text) {
            var div = document.getElementById('tbxdanhsachthietbi');
            var nextSibling = div.nextSibling.nextSibling.children[1];
            var sText = '';
            nextSibling.style.color = 'blue';
            sText = nextSibling.firstChild.nodeValue;
            sText = sText + text;
            nextSibling.innerHTML = '';
            nextSibling.innerHTML = sText;
        },
        GetDisplayMarker: function () {
            nDisplay = Tracking.Core.Browser.getCookie('nDisplay');
            if (nDisplay == undefined || nDisplay == null || nDisplay == 0) {
                nDisplay = 0;
                nIconH = 32;
                nIconW = 32;
            }
            if (nDisplay == 1) {
                nIconH = 50;
                nIconW = 50;
            }
            if (nDisplay == 2) {
                nIconH = 75;
                nIconW = 75;
            }

        },
        SetDisplay: function () {
            var var_name = $(":radio:checked").val();
            if (var_name.indexOf('Id') != -1) {
                nDisplay = 1;
                nIconH = 50;
                nIconW = 50;
            }
            else if (var_name.indexOf('PlateNumber') != -1) {
                nDisplay = 2;
                nIconH = 75;
                nIconW = 75;
            }
            else {
                nDisplay = 0;
                nIconH = 32;
                nIconW = 32;
            }
            Tracking.Core.Browser.setCookie('nDisplay', nDisplay, 365);
            Tracking.Core.Init.GetDevices();

        },
        RefreshDataForGrid: function () {
            jQuery('#tbDanhSachThietBi').setGridParam().trigger('reloadGrid');
        },
        RefreshDevice: function () {
            //map.checkResize();
            Tracking.Core.Init.GetDevices();

        },
        ClearTimeOut: function () {
            clearInterval(timeIntervalRefreshGrid);
            clearInterval(timeRefresDevice);
        },
        ResizeDataGrid: function (hcontainer) {
            var hs = $(window).height();
            var hbottom = $('#divOnTop').height();

            var htabcontain = $('#tab').height();
            $('#' + hcontainer + ' .datagrid-wrap').height(htabcontain - 30); //30 la paging
            $('#' + hcontainer + ' .datagrid-pager').offset({ top: $(window).height() - (hbottom + 30), left: 0 }); //50: 30(paging) + 20 bottom window

        },
        OpenWindow: function (type, url, div, title, width, height, mode, coll, min, max, close, resize, drag, icon, idchild) {
            bActiveWindow = true;
            if (type == 1) {

                $('#' + div).window({ //window
                    href: url,
                    title: title,
                    width: width,
                    height: height,
                    modal: mode,
                    collapsible: coll,
                    minimizable: min,
                    maximizable: max,
                    closable: close,
                    resizable: resize,
                    draggable: drag,
                    cache: false,
                    iconCls: icon,
                    onClose: function () {

                        flagAddPositionInputInfo = false;
                        flagUpdateNhapThongTin = false;
                        bActiveWindow = false;
                        $('#cbNguoiDung').combobox('reload');
                    },
                    onLoad: function () {

                    },
                    onMaximize: function () {
                        switch (idchild) {
                            case 1:
                                {
                                    Tracking.Core.Processor.ResizeWindow('quanly', 'dataGrid', delta);
                                    break;
                                }
                        }
                    },
                    onRestore: function () {
                        switch (idchild) {
                            case 1:
                                {
                                    Tracking.Core.Processor.ResizeWindow('quanly', 'dataGrid', delta);
                                    break;
                                }
                        }
                    }

                });
            }
            else if (type == 2) { //dialog

                $('#' + div).dialog({
                    href: url,
                    title: title,
                    width: width,
                    height: height,
                    modal: mode,
                    collapsible: coll,
                    minimizable: min,
                    maximizable: max,
                    closable: close,
                    resizable: resize,
                    draggable: drag,
                    cache: false,
                    iconCls: icon,
                    onClose: function () {

                        flagAddTab = false;
                        bActiveWindow = false;
                        Tracking.Core.Browser.setCookie('AlertSpeed', ($(txtSpeed).val()), 5);
                    }
                });
            }

        },
        CloseWindow: function (type, div) {

            type == 1 ? $('#' + div).window('close') : $('#' + div).dialog('close');
            // type == 1 ? $('#' + div).window('destroy') : $('#' + div).dialog('destroy');

        },

        ClearVehicleMk: function () {
            if (markerSelectet == 0) {
                for (var i = 0; i < arrVehicleMk.length; i++) {
                    map.removeOverlay(arrVehicleMk[i]);
                    arrVehicleMk[i] = null;
                }
                arrVehicleMk = new Array();
            }
            else {
                for (var i = 0; i < arrVehicleMk.length; i++) {
                    if (arrVehicleMk[i].IsActive != true) {
                        map.removeOverlay(arrVehicleMk[i]);
                        arrVehicleMk[i] = null;
                    }
                }
                arrVehicleMk.length = 1;
            }

        },
        ClearAllVehicleMk: function () {
            for (var i = 0; i < arrVehicleMk.length; i++) {
                map.removeOverlay(arrVehicleMk[i]);
                arrVehicleMk[i] = null;
            }
            arrVehicleMk = new Array();
        },
        GetIndexInVehicleMK: function (DeviceID) {
            if (objDevices.length > 0) {
                for (i = 0; i < objDevices.length; i++) {
                    if (objDevices[i].ID == DeviceID) {
                        return i;
                    }
                }
                return -1;
            }
        },
        CloseAndOpenTab: function (idcheck, tabName, title, href, content, icon, closable, selected, id) {
            flagAddTab = true;
            if (idcheck.checked == true) {
                Tracking.Core.Interface.CreateTab(tabName, title, href, content, icon, closable, selected, id);
                var tab = $('#' + tabName).tabs('exists', title);
                if (tab) {

                    $('#' + tabName).tabs({ onSelect: function (t, index) {

                        Tracking.Core.Processor.GetSelectedTab(tabName, title);
                    }

                    });

                }
            }
            else {
                Tracking.Core.Interface.CloseTab(tabName, title);
            }

        },
        GetSelectedTab: function (tabName, title) {
            var tab = $('#' + tabName).tabs('exists', title);
            var tabs = $('#' + tabName).tabs('getSelected');
            titleTab = tabs.panel('options').title;
            Tracking.Core.Processor.SwitchTab(tabName, titleTab);
        },

        SwitchTab: function (tabName, title) {
            //if (flagAddTab) {
            // var tab = $('#' + tabName).tabs('exists', title);
            // if (tab == true) {
            switch (title) {
                case 'Xem lại lộ trình':
                    {
                        //Xoa các proccessor cua tab khác
                        SELECT_TAB = 1;
                        Tracking.Core.Processor.ClearAllOverlay();
                        Tracking.Core.Processor.ClearTimeOut();
                        $('#totalDistant').html('');

                        $('#tbXemlailotrinh').datagrid('loadData', { "total": 0, "rows": [] });
                        break;
                    }
                case 'Danh sách vùng':
                    {
                        SELECT_TAB = 2;
                        Tracking.Core.Processor.ClearTimeOut();
                        break;
                    }
                case 'Kết quả tìm đường':
                    {
                        Tracking.Core.Processor.ClearTimeOut();
                        break;
                    }
                case 'Kết quả tìm nhóm thiết bị':
                    {
                        Tracking.Core.Processor.ClearTimeOut();
                        map.clearOverlays();
                        break;
                    }
                case 'Quản lý thư điện tử':
                    {
                        Tracking.Core.Processor.ClearTimeOut();
                        break;
                    }
                case 'Quản lý tin nhắn':
                    {
                        Tracking.Core.Processor.ClearTimeOut();
                        break;
                    }
                case 'Danh sách thiết bị':
                    {
                        SELECT_TAB = 0;
                        Tracking.Core.Processor.ClearAllOverlay();
                        Tracking.Core.Init.GetDevices();
                        timeIntervalRefreshGrid = setInterval('Tracking.Core.Processor.RefreshDataForGrid();', nTimeInterValGrid);
                        timeRefresDevice = setInterval('Tracking.Core.Processor.RefreshDevice();', nTimeInterValDevice);
                        Tracking.Core.Interface.UnSelectRecord('tbDanhSachThietBi');
                        break;
                    }
                case 'Nhập thông tin':
                    {
                        Tracking.Core.Processor.ClearTimeOut();
                        break;
                    }
                default:
                    {

                        break;
                    }
            }

            setTimeout('Tracking.Core.Processor.ResizeDataGrid(\"south\")', 800); //Dung de resize tat ca cac gridview
            //  }

            // }

        },
        LogOut: function () {

            Tracking.Core.Browser.setCookie('Logout', '', 1);
            $.ajax({
                'type': 'POST',
                'url': 'ServiceTracking.asmx/LogOut',
                dataType: "json",
                //data: { 'param': session, id: id.id },
                async: true,
                success: function (msg) {
                    if (msg.result == true) {

                        window.location.href = 'Login.aspx?ReturnUrl=Default.aspx';
                    }
                }
            });
            window.location.href = 'Login.aspx?ReturnUrl=Default.aspx';
        },
        Login: function () {
            var username = $('#txtUserName').val();
            var password = $('#txtPassword').val();
            var url = location.hostname;
            $.ajax({
                'type': 'POST',
                //'url': 'Service/Login.ashx',
                url: 'ServiceTracking.asmx/Login',
                data: { 'User': username, 'Pass': password, 'Url': url },
                dataType: "json",
                async: true,
                success: function (msg) {
                    try {
                        if (msg.result == true) {
                            Tracking.Core.Browser.setCookie('Logout', username, 1);
                            window.location.href = 'Default.aspx';

                        }
                        else {

                            $('#info').html('Người dùng hoặc mã số không đúng!');
                            $('#txtUserName').val('');
                            $('#txtPassword').val('');
                            $('#txtUserName').focus();
                            return;
                        }
                    }
                    catch (e) {

                        // window.location.href = 'Default.aspx';
                    }

                }
                /*error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#info').html('Người dùng hoặc mã số không đúng!');
                return;
                }*/
            });
        },
        OnKeyPressLogin: function (event) {
            if (event.keyCode == 13) {
                Tracking.Core.Processor.Login();
            }
            else {

                return;
            }

        },
        OnKeyPressSearchDevice: function (event) {
            if (event.keyCode == 13) {
                Tracking.Core.Business.SearchDevice();
            }
            else {

                return;
            }

        },
        ResizeWindow: function (parent, child, delta) {

            var hparent = $('#' + parent).height();
            var hchild = $('#' + child).height();
            if (hparent - delta > hchild) {
                $('#' + child).height(hparent - delta);
            }
            else {
                $('#' + child).height(hparent - delta);
                $('#' + child).css('overflow', 'auto');
            };
        },
        ResizeTableScrollBar: function (divparent, divchild, talble, delta) {
            var hparent = $('#' + divparent).height();
            var hchild = $('#' + divchild).height();

            if (hparent > hchild - delta) {
                $('#' + talble).datagrid({
                    scrollbarSize: 1
                });
            }
            else {
                $('#' + talble).datagrid({
                    scrollbarSize: 18
                });
            };
        },
        LuuTabs: function () {

            // Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/LuuTabs','','','POST',true,'json', 'application/json; charset=utf-8');
        },
        BindEventForTab: function () {
            $(function () {
                $('#tab ul li').bind('click', function () { Tracking.Core.Processor.SwitchTab('tab', ($(this).text())) });
            });
        },
        ClearAllOverlay: function () {
            map.clearOverlays();
            //Khoi tao lai mang MK
            arrVehicleMk = new Array();
        },
        GetNumPageSelectMKDevice: function (deviceid, pagesize) {
            var pData = "{ param:\"{deviceid:'" + deviceid + "',pagesize:'" + pagesize + "'}\"}";
            Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/GetNumberPageSelectMarkerDevice', pData, Tracking.Core.Processor.SelectRecoredInGridDevice, 'POST', 'true', 'json', 'application/json; charset=utf-8');
        },
        SelectRecoredInGridDevice: function (data) {
            if (data) {
                data = eval("(" + data.d + ")"); //Convert data la 1 string toi 1 object la Json
                var obj = GetInfoPager(data.index, 'tbDanhSachThietBi');
                $('#tbDanhSachThietBi').setGridParam({ page: obj.Page }).trigger("reloadGrid");
            }
        },
        //Xem lai lo trinh
        LoadDataDeviceToCombo: function () {
            $('#selectSearch').combobox({
                url: 'Service/Option/CbDevices.ashx',
                valueField: 'ID',
                textField: 'Device'
            });
        },
        LoadDataUserToCombo: function () {
            $('#cbNguoiDung').combobox({
                url: 'Service/Option/CbNguoiDung.ashx',
                valueField: 'ID',
                textField: 'Name'
            });
        },
        GetMarkerRouterCallback: function (data) {
            Tracking.Core.Processor.ClearAllOverlay();

            if (data.length > 2) {
                nPoint = data.length;
                var nW = 13;
                var strCls = ' ngreen';
                map.setCenter(new VLatLng(parseFloat(data[2].Latidue), parseFloat(data[2].Longtitude)), map.getLevel());

                //Tạo marker
                for (var i = 0; i < data.length; i++) {
                    nW = (i.toString().length + 1) * 6;
                    var latlng = new VLatLng(parseFloat(data[i].Latidue), parseFloat(data[i].Longtitude));
                    var mopt = new VMarkerOptions(new VIcon('', new VSize(nW, 13)));
                    mopt.offset = new VSize(Math.round(nW / 2), 13);
                    mopt.customMarker = '<a class="NumberMarker' + strCls + '"><span>' + (i + 1) + '</span></a>';
                    arrMarkerRouter[i] = new VMarker(latlng, mopt);
                    arrMarkerRouter[i].vOrder = i;
                    arrMarkerRouter[i].type = MKROUTER;
                    map.addOverlay(arrMarkerRouter[i]);

                }
                CurentPoint = new VMarker(new VLatLng(data[0].Latidue, data[0].Longtitude), new VIcon('Service/Utilities/ResizeImageCaching.ashx?p=images/GPS/blue_000.png&h=32&w=32&auto=false&headding=' + data[0].Headding, new VSize(32, 32)));
                Tracking.Core.Processor.DrawPathRouter(data);
            }
        },
        DrawPathRouter: function (data) {
            arrMarkerRouter = new Array();
            arrPath = new Array();
            arrLine = new Array();
            if (data.length > 2) {
                //Tạo mảng điểm
                for (var i = 0; i < data.length; i++) {
                    arrPath[i] = new VLatLng(data[i].Latidue, data[i].Longtitude);
                }
                //Vẽ polyline: co 2 cách. 1: truyen 1 tap mang diem ve 1 lần. 2: truyen từng đoạn.
                var line = new Array();
                for (var j = 0; j < arrPath.length - 1; j++) {
                    line = new Array();
                    line.push(arrPath[j]);
                    line.push(arrPath[j + 1]);
                    arrLine[j] = new VPolyline(line, "#429641", 3, "", 0.6);
                    arrLine[j].vOrder = j;
                    arrLine[j].type = LINEROUTER;
                    arrLine[j].Headding = data[j].Headding;
                    map.addOverlay(arrLine[j]);
                }
                Index = 0;
                //Vẽ mũi tên
                var arrow = new VArrow(arrPath, 'middle', '#F9793C', 2, 0.6);
                map.addOverlay(arrow);

                // Tinh tổng khoản cách lộ trình: Phải get mang diem của lo trình
                var totalLng = Tracking.Core.Utility.GetLength(arrPath);
                var stotalLng = Tracking.Core.Utility.FormatDistant(totalLng);
                $('#totalDistant').html('Tổng chiều dài: <b>' + stotalLng + '</b>');

            }
            map.addOverlay(CurentPoint);

        },

        GetUserNameAndPasswordCallback: function (data) {
            if (data) {
                data = eval("(" + data + ")");
                var nReUP = Tracking.Core.Browser.getCookie('remember_user_pass');
                if (nReUP == 1) {
                    $('#txtUserName').val(data.username);
                    $('#txtPassword').val(data.password);
                    $('#chkrUP').attr('checked', true);
                    var nAuto = Tracking.Core.Browser.getCookie('remember_auto');
                    if (nAuto == 1 && nAuto != undefined) {
                        $('#chkrAuto').attr('checked', true);
                    }
                    setTimeout('Tracking.Core.Processor.AutoLogin();', 5000);
                }
                else {
                    $('#chkrUP').attr('checked', false);
                    $('#txtUserName').focus();
                    $('#txtUserName').val('');
                    $('#txtPassword').val('');
                }
            }
            return;
        },
        AutoLogin: function () {
            if ($('#txtUserName').val() != '' && $('#txtPassword').val() != '') {
                if ($('#chkrAuto').is(':checked')) {
                    Tracking.Core.Processor.Login();
                }
                else {
                    $('#chkrAuto').attr('checked', false);
                }

            }
        },
        SelectPasswordAndAuto: function () {
            if ($('#chkrUP').is(':checked')) {
                Tracking.Core.Browser.setCookie('remember_user_pass', 1, 1000);
            }
            else {
                Tracking.Core.Browser.setCookie('remember_user_pass', 0, 1);
            }
            if ($('#chkrAuto').is(':checked')) {
                Tracking.Core.Browser.setCookie('remember_auto', 1, 1000);
            }
            else {
                Tracking.Core.Browser.setCookie('remember_auto', 0, 1);
            }
        },
        SetStatusVehicles: function () {

            nBlue = ($('#chkblue').is(':checked')) ? 1 : 0;
            nRed = ($('#chkred').is(':checked')) ? 1 : 0;
            nYellow = ($('#checkyellow').is(':checked')) ? 1 : 0;
            nGray = ($('#chkgrey').is(':checked')) ? 1 : 0;
            //Tracking.Core.Processor.ClearVehicleMk();
            Tracking.Core.Init.GetDevices();
        },
        SelectRecordInGrid: function (grid, index) {
            $('#' + grid).datagrid('selectRow', index);
        },
        ShowSOS: function (data) {

            if (data.ID == 1) {
                $.messager.show({
                    title: 'Cảnh báo SOS',
                    msg: 'Message will be closed after 5 seconds.',
                    timeout: 5000,
                    showType: 'show'
                });
            }

        },
        GetDeviceDetailByTrackID: function (trackid) {
            nBuleClick = 0;
            nRedClick = 0;
            nYellowClick = 0;
            nGrayClick = 0;
            var param = "{param:\"{trackid:'" + trackid + "'}\"}"; ;
            Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/GetDeviceInfoByTrackID', param, Tracking.Core.Processor.GetDeviceDetailByTrackIDCallBack, 'POST', true, 'json', 'application/json; charset=utf-8');

        },

        GetDeviceDetailByTrackIDCallBack: function (data) {

            data = data.d;
            var obj = new Object();
            obj.Latidue = data.Latidue;
            obj.Longtitude = data.Longtitude;
            obj.ID = data.ID;
            obj.TrackID = data.TrackID;
            obj.PlateNumber = data.PlateNumber;
            obj.index = 0;
            obj.GPS = 'A';
            obj.SOS = data.SOS;
            obj.Phone = data.Phone;
            obj.Door = data.Door;
            obj.FuelVolume = data.FuelVolume;
            obj.Engine = data.Engine;
            obj.Air = data.Air;
            obj.Headding = data.Headding;

            if (data.Speed == null || data.Speed == undefined) {
                obj.Speed = 0;
            } else {
                obj.Speed = data.Speed;
            }

            Tracking.Core.Interface.CreateNewOneMarkerDevice(obj, obj.index);
            Tracking.Core.Interface.ShowVehicleWindow(obj, obj.index);
            if (obj.GPS == 'A' && obj.Speed == 0) {
                nRedClick = 1;
            }
            else if (obj.GPS == 'A' && obj.Speed > 0) {
                nBuleClick = 1;
            }
            else if (obj.GPS == 'V') {
                nYellowClick = 1;
            }
            else if (obj.GPS == 'N') {
                nGrayClick = 1;
            }
        },
        GetInfoCompanyCallBack: function (data) {
            data = data.d;
            if (data.Logo != null) {
                $('.logo').css('background', 'url(' + data.Logo + ') no-repeat 10px 5px');
                $('#logo').attr('href', location.href);
            }
            var v_css = document.createElement("link");
            v_css.rel = "shortcut icon";
            if (data.Icon != null)
                v_css.href = data.Icon;
            document.getElementsByTagName('head')[0].appendChild(v_css);

            Tracking.Core.Processor.DisplaySupportOnline(data);
        },
        DisplaySupportOnline: function (data) {
            var sEmail = data.Emails;
            var sChatNicks = data.ChatNicks;
            var sPhone = data.Telephones;
            var arrEmail = new Array();
            if (sEmail != null) {
                arrEmail = sEmail.split(',');
            }
            var arrChatNick = new Array();
            if (sChatNicks != null) {
                arrChatNick = sChatNicks.split(',');
            }
            var arrPhone = new Array();
            if (sPhone != null) {
                arrPhone = sPhone.split(',');
            }
            var arrHTML = new Array();
            if (arrPhone.length > 1) {
                arrHTML[arrHTML.length] = '<span class="lblSupport">';
                arrHTML[arrHTML.length] = '- Hỗ trợ kinh doanh:';
                arrHTML[arrHTML.length] = '</span> <b style="color: #FF0000">';
                arrHTML[arrHTML.length] = arrPhone[0];
                arrHTML[arrHTML.length] = '</b>';
                arrHTML[arrHTML.length] = '<br />';
                if (arrPhone.length > 1) {
                    arrHTML[arrHTML.length] = '<span class="lblSupport">';
                    arrHTML[arrHTML.length] = '- Hỗ trợ kỹ thuật:';
                    arrHTML[arrHTML.length] = '</span><b style="color: #FF0000">';
                    arrHTML[arrHTML.length] = arrPhone[1]; ;
                    arrHTML[arrHTML.length] = '</b>';
                    arrHTML[arrHTML.length] = '<br />';
                }

            }
            if (arrChatNick.length > 1) {
                if (arrChatNick.length == 1) {
                    if (arrChatNick[0].indexOf('@yahoo.com') != -1) {
                        var arrNick = arrChatNick[0].split('@');
                        arrHTML[arrHTML.length] = '<span><a href="ymsgr:sendIM?';
                        arrHTML[arrHTML.length] = arrNick[0];
                        arrHTML[arrHTML.length] = '">';
                        arrHTML[arrHTML.length] = '<img src="http://opi.yahoo.com/online?u=';
                        arrHTML[arrHTML.length] = arrNick[0];
                        arrHTML[arrHTML.length] = '&amp;m=g&amp;t=1" border="0"></a></span>';
                    }
                    else {
                        arrHTML[arrHTML.length] = '<a href=skype:';
                        arrHTML[arrHTML.length] = arrChatNick[0];
                        arrHTML[arrHTML.length] = '</a>';
                    }
                    arrHTML[arrHTML.length] = '<br/>';
                }
                if (arrChatNick.length == 2) {
                    if (arrChatNick[0].indexOf('@yahoo.com') != -1) {
                        var arrNick = arrChatNick[0].split('@');
                        arrHTML[arrHTML.length] = '<span><a href="ymsgr:sendIM?';
                        arrHTML[arrHTML.length] = arrNick[0];
                        arrHTML[arrHTML.length] = '">';
                        arrHTML[arrHTML.length] = '<img src="http://opi.yahoo.com/online?u=';
                        arrHTML[arrHTML.length] = arrNick[0];
                        arrHTML[arrHTML.length] = '&amp;m=g&amp;t=1" border="0"></a></span>';
                    }
                    else {
                        arrHTML[arrHTML.length] = '<a href=skype:';
                        arrHTML[arrHTML.length] = arrChatNick[1];
                        arrHTML[arrHTML.length] = '</a>';
                    }
                    arrHTML[arrHTML.length] = '<br/>';
                }


            }
            if (arrEmail.length > 1) {
                arrHTML[arrHTML.length] = '<b class="lblSupport"> - Email:</b> <span class="linkSupport"><a  href="mailto:';
                arrHTML[arrHTML.length] = arrEmail[0];
                arrHTML[arrHTML.length] = '">';
                arrHTML[arrHTML.length] = arrEmail[0];
                arrHTML[arrHTML.length] = '</a></span>';

            }
            $('#supportonline').html(arrHTML.join(''));

        }

    }, //End Processor

    /* Begin Interface: Display Form, label, text ...... (Much dich cua lop nay la: thuc hien hien thi tat ca cac object ve giao dien)*/
    Interface: {
        /*Begin Quan ly nguoi dung */
        //Hien thi Form Edit-Add User
        Edit_AddUserForm: function (type) {
            var title = '';
            $('#EditUser').css('display', 'block');
            if (type == 1) {
                flagAdd_EditNguoiDung = false;
                Tracking.Core.Processor.OpenWindow(2, '', 'EditUser', 'Thêm mới User', 620, 220, true, '', '', '', true, '', true, 'icon-add'); //Goi tao window truoc Tiep theo moi mo. 
                title = 'Thêm mới User';
                $('#txtTenTaiKhoan').removeAttr('readonly', 'readonly');
                $('#txtTenTaiKhoan').addClass('tb10');
                $('#txtTenTaiKhoan').val('');
                $('#txtTenHienThi').val('');
                $('#txtNguoiCap').val(Tracking.Core.Browser.getCookie('Logout'));

                $('#txtDienThoai').val();
                $('#txtPassword').val('');
                $('#txtEmail').val('');
            }
            if (type == 2) {
                flagAdd_EditNguoiDung = true;
                var rowdata = $('#ListUser').datagrid('getSelected');

                if (rowdata == null || rowdata == 'undefined') {
                    $.messager.alert('Thông báo!', 'Vui lòng chọn dòng dữ liệu cần cập nhật!', 'info');
                    return;
                }
                else {
                    title = 'Cập nhật User';
                    Tracking.Core.Processor.OpenWindow(2, '', 'EditUser', 'Cập nhật User', 620, 220, true, '', '', '', true, '', true, 'icon-edit'); //Goi tao window truoc Tiep theo moi mo. 
                    $('#txtTenTaiKhoan').val(rowdata.Name);
                    $('#txtTenTaiKhoan').attr('readonly', 'readonly');
                    $('#txtTenTaiKhoan').removeClass('tb10');
                    $('#txtTenTaiKhoan').addClass('tb10-readonly');
                    $('#txtTenHienThi').val(rowdata.ContactFullName);
                    $('#txtNguoiCap').val(rowdata.ParentName);
                    $('#txtNguoiCap').attr('readonly', 'readonly');
                    $('#txtDienThoai').val(rowdata.ContactCellPhone);
                    //$('#txtQuyen').val(rowdata.Permission);
                    //$('#txtQuyen').attr('readonly', 'readonly');
                    $('#txtEmail').val(rowdata.ContactEmail);
                    $('#hdIdNguoidung').val(rowdata.ID);
                    //var ck = rowdata.Active;
                    //(ck.indexOf('checked=checked') != -1) ? $('#chkKichHoat').attr('checked', 'checked') : $('#chkKichHoat').removeAttr('checked', 'checked');
                }

            }

            $('#EditUser').dialog('open');
            $('#EditUser').dialog('setTitle', title);
            $('#txtNguoiCap').attr('readonly', 'readonly');
        },
        //Hien thi Form quan ly nguoi dung
        ManagerUserForm: function () {
            Tracking.Core.Processor.OpenWindow(1, 'QuanLy/DanhSachNguoiDung.aspx', 'quanly', 'Danh sách người dùng', 750, 450, true, false, false, false, true, false, true, 'icon-quanlyuser');
        },
        ThongTinNguoiDung: function () {
            Tracking.Core.Processor.OpenWindow(1, 'QuanLy/ThongTinNguoiDung.aspx', 'quanly', 'Thông tin người dùng', 310, 260, true, false, false, false, true, false, true, 'icon-quanlyuser');
        },
        ChangePassWord: function () {
            $('#changePassword').css('display', 'block');
            Tracking.Core.Processor.OpenWindow(2, '', 'changePassword', 'Đổi mật khẩu người dùng', 360, 170, true, false, false, false, true, false, true, 'icon-quanlyuser');
            $('#changePassword').dialog('open');
        },
        /* End quan ly nguoi dung*/

        /* Xu ly hien thi Market */
        //Tao marker
        CreateMarkerDevice: function (data) {
            Tracking.Core.Processor.ClearVehicleMk();
            var nCount = 0;
            if (data) {
                data = JSON.parse(data); //data = eval("(" + data + ")"); //Convert data la 1 string toi 1 object la Json
                if (data.length > 0) { // Devices la ten table truong hop la Data la 1 DataSet thi data.Devices.length con neu data la 1 table thi data.length 
                    objDevices = data;
                    for (var i = 0; i < data.length; i++) {
                        if (markerSelectet == 0) {
                            Tracking.Core.Interface.CreateNewOneMarkerDevice(data[i], i);
                        }
                        else {
                            if (markerSelectet != data[i].TrackID) {
                                Tracking.Core.Interface.CreateNewOneMarkerDevice(data[i], nCount + 1);
                                nCount++; //Khong dung bien i vi neu truong hop ma trung k tao duoc marker neu theo bien i thi arrVehicle van tao 1 phan tu underfind
                            }
                            else {
                                Tracking.Core.Interface.UpdatePositionAndStatusMK(data[i]);
                            }

                        }
                    }

                }
            }

            var objData = new Object();
            objData.CarBlue = nNumBlue + nBuleClick;
            objData.CarRed = nNumRed + nRedClick;
            objData.CarYellow = nNumYellow + nYellowClick;
            objData.CarYellow = nNumGrey + nGrayClick;
            Tracking.Core.Interface.VehicleStatus(objData);

        },

        CreateNewOneMarkerDevice: function (obj, i) {

            var strFN = 1;
            var nHeadding = 0;
            var sPathImage = 'Service/Utilities/ImagesMarker.ashx?p=';
            nHeadding = obj.Headding;

            if (obj.Headding == undefined) {
                strFN = 4;
                /*strFN = "images/GPS/grey_";
                strFN += '000';
                strFN += ".png";*/
                nNumGrey++;

            } else if (obj.GPS == 'A' && nBlue == 1 && obj.Speed > 0) {
                /*strFN = "images/GPS/blue_";
                strFN += '000';
                strFN += ".png";*/
                strFN = 1;
                nNumBlue++;

            } else if (obj.GPS == 'A' && nRed == 1 && obj.Speed == 0) {
                /*strFN = "images/GPS/red_";
                strFN += '000';
                strFN += ".png";*/
                strFN = 2;
                nNumRed++;

            } else if (obj.GPS == 'V' && nYellow == 1) {
                /*strFN = "images/GPS/yellow_";
                strFN += '000';
                strFN += ".png";
                */
                strFN = 3;
                nNumYellow++;

            } else if (obj.GPS == 'N' && nGray == 1) {
                /*strFN = "images/GPS/grey_";
                strFN += '000';
                strFN += ".png";
                */
                strFN = 4;
                nNumGrey++;

            }

            var ll = new VLatLng(parseFloat(obj.Latidue), parseFloat(obj.Longtitude));
            var mopt = Object();
            if (nDisplay == 2) {

                if (obj.PlateNumber != "") {
                    //mopt = new VMarkerOptions(new VIcon(sPathImage + strFN + '&DeviceID=' + obj.ID + '&auto=' + 'false' + '&Headding=' + nHeadding, new VSize(nIconW, nIconH)), obj.PlateNumber, [new VTextPosition(V_ANCHOR_TOP_CENTER, new VSize(0, 1))], [new VTextStyle(12, 'bold', '#FC0203', 'Verdana')]);
                    nIconH = 75;
                    nIconW = 75;

                }
                else {
                    nIconH = 32;
                    nIconW = 32;
                }
            }

            mopt = new VMarkerOptions(new VIcon(sPathImage + strFN + '&DeviceID=' + obj.ID + '&auto=' + 'false' + '&Headding=' + nHeadding + '&d=' + nDisplay + '&PlateNumber=' + obj.PlateNumber, new VSize(nIconW, nIconH)));
            mopt.offset = new VSize(parseInt(nIconH / 2), parseInt(nIconW / 2));
            arrVehicleMk[i] = new VMarker(ll, mopt);
            arrVehicleMk[i].vOrder = obj.TrackID;
            arrVehicleMk[i].type = VEHICLEOBJ;
            arrVehicleMk[i].index = i;
            arrVehicleMk[i].IsActive = false;
            arrVehicleMk[i].DeviceID = obj.ID;
            map.addOverlay(arrVehicleMk[i]);

            //Them phan tooltip
            $('.tipsy').remove();
            var strTitMCode = (nLg == 0) ? "Mã nhà sản xuất" : "Manufacturer code";
            var strTitDCode = (nLg == 0) ? "Mã thiết bị" : "Device code";
            var strPlatenumber = (nLg == 0) ? "Số xe" : "Plate Number";
            var tipHTML = '<div style="white-space:normal;text-align:left;padding:5px">';
            //tipHTML += '<i>' + strTitMCode + '</i> : ' + 'Omeitrack' + '<br/>';
            if (obj.PlateNumber != '' || obj.PlateNumber != '') {
                tipHTML += '<i>' + strPlatenumber + '</i> : ' + 'Omeitrack' + '<br/>';
            }
            tipHTML += '<i>' + strTitDCode + '</i> : ' + obj.ID + '</div>';

            $('#' + arrVehicleMk[i].id).attr('title', tipHTML);

            VEvent.addListener(arrVehicleMk[i], "mouseover", function (overlay, pt) {
                $('#' + overlay.id).ShowTipsy();

            });

            VEvent.addListener(arrVehicleMk[i], "mouseout", function (overlay, pt) {
                $('#' + overlay.id).HideTipsy();

            });



        },
        ShowVehicleWindow: function (obj, index) {
            //Can goi len Server de lay thong tin cua thiet bi
            markerSelectet = obj.TrackID;
            var info = new Array();
            info[info.length] = '<div class="MiniPopup">';
            info[info.length] = '<span class="Title">' + obj.ID;
            info[info.length] = '</span><p class="Content">';
            // info[info.length] = '<span class="address"><i> Mã nhà sản xuất: </i>' + objDevices[i].VendorID + '</span>';
            // info[info.length] = '<span class="address"><i> Trạng thái : </i>' + obj.ID + '</span>';
            // info[info.length] = '<span class="address"><i> Nhiên liệu : </i>' + obj.FuelVolume + '</span>';
            var sSpeed = 0;
            if (obj.Speed != undefined) {
                sSpeed = obj.Speed;
            }
            info[info.length] = '<span class="address"><i> Vận tốc : </i>' + sSpeed + '</span>';
            var sDoor = (obj.Door == false) ? 'Đóng' : 'Mở';
            var sAir = (obj.Air == true) ? 'Bật' : 'Tắt';
            var sEngine = (obj.Engine == true) ? 'Bật' : 'Tắt';
            info[info.length] = '<span class="address"><i> Cửa : </i>' + sDoor + '</span>';
            info[info.length] = '<span class="address"><i> Máy lạnh : </i>' + sAir + '</span>';
            info[info.length] = '<span class="address"><i> Động cơ : </i>' + sEngine + '</span>';
            info[info.length] = '</p>';
            info[info.length] = '</div>';
            var iwOpt = new VInfoWindowOptions(new VSize(0, -8));
            arrVehicleMk[index].openInfoWindow(info.join(""), iwOpt);
            arrVehicleMk[index].IsActive = true;
            flZoom = true;

        },
        UpdatePositionAndStatusMK: function (data) {
            var strFN = 1;
            nBuleClick = 0;
            nRedClick = 0;
            nYellowClick = 0;
            nGrayClick = 0;
            var nHeadding = data.Headding;
            if (data.Headding == 0 || data.Headding == undefined) {
                /*strFN = "images/GPS/grey_";
                strFN += '000';
                strFN += ".png";*/
                strFN = 4;
                nGrayClick = 1;
            }
            else if (data.GPS == 'A' && nBlue == 1 && data.Speed > 0) {
                /*strFN = "images/GPS/blue_";
                strFN += '000';
                strFN += ".png";*/
                strFN = 1;
                nBuleClick = 1;
            }
            else if (data.GPS == 'A' && nRed == 1 && data.Speed == 0) {

                /*strFN = "images/GPS/red_";
                strFN += '000';
                strFN += ".png";*/
                strFN = 2;
                nRedClick = 1;
            }
            else if (data.GPS == 'V' && nYellow == 1) {
                /* strFN = "images/GPS/yellow_";
                strFN += '000';
                strFN += ".png";*/
                strFN = 3;
                nYellowClick = 1;
            }
            else if (data.GPS == 'N' && nGray == 1) {
                /*strFN = "images/GPS/grey_";
                strFN += '000';
                strFN += ".png";*/
                strFN = 4;
                nGrayClick = 1;
            }

            if (arrVehicleMk[0] != undefined) {
                var rect = Tracking.RoadMap.Rect();
                arrVehicleMk[0].setPoint(new VLatLng(parseFloat(data.Latidue), parseFloat(data.Longtitude)));
                if ((arrVehicleMk[0].latlngs.latitude < rect.dMinLat) || (arrVehicleMk[0].latlngs.latitude > rect.dMaxLat) || (arrVehicleMk[0].latlngs.longitude < rect.dMinLng) || (arrVehicleMk[0].latlngs.longitude > rect.dMaxLng)) {
                    map.setCenter(new VLatLng(arrVehicleMk[0].latlngs.latitude, arrVehicleMk[0].latlngs.longitude), rect.Level);
                }

                var sPathImage = 'Service/Utilities/ImagesMarker.ashx?p=';
                /* if (data.PlateNumber.length > 0) {
                arrVehicleMk[0].setIcon(new VIcon(sPathImage + strFN + '&DeviceID=' + data.ID + '&auto=' + 'false' + '&Headding=' + nHeadding, new VSize(nIconW, nIconH)), obj.PlateNumber, [new VTextPosition(V_ANCHOR_TOP_CENTER, new VSize(0, 1))], [new VTextStyle(12, 'bold', '#FC0203', 'Verdana')]);
                }*/

                arrVehicleMk[0].setIcon(new VIcon(sPathImage + strFN + '&DeviceID=' + data.ID + '&auto=' + 'false' + '&Headding=' + nHeadding + '&d=' + nDisplay + '&PlateNumber=' + data.PlateNumber), new VSize(nIconW, nIconH));
            }


        },
        /* End xu ly Marker */

        //Create Tab
        CreateTab: function (tabName, title, href, content, icon, closable, selected, id) {
            try {
                $(function () {
                    var tab = $('#' + tabName).tabs('exists', title);
                    if (tab == true) {
                        $.messager.alert('Thông báo!', 'Tùy chọn này đã có rồi!');
                    }
                    else {
                        $('#' + tabName).tabs('add', {
                            title: title,
                            iconCls: icon,
                            content: content,
                            href: href,
                            closable: closable,
                            cache: false,
                            selected: selected,
                            id: 'tab' + id

                        });

                    }
                });

            } catch (e) {
                alert('error CreateTab');
            }

        },
        OptionAddTab: function () {
            $('#AddTab').css('display', 'block');

            Tracking.Core.Processor.OpenWindow(2, '', 'AddTab', 'Thêm tùy chọn', 170, 170, true); //Goi tao window truoc Tiep theo moi mo. 
            $('#AddTab').window('open');
        },
        CloseTab: function (tabName, index) {
            //Ckeck Exists
            var tab = $('#' + tabName).tabs('exists', index);
            if (tab == true) {
                $('#' + tabName).tabs('close', index);

            }
            else {
                return;
            }
        },

        ViewFormHistoryUser: function () {
            Tracking.Core.Processor.OpenWindow(1, 'Quanly/Lichsutruycap.aspx', 'quanly', 'Lịch sử truy cập người dùng', 530, 300, true, false, false, false, true, false, true, 'icon-lichsunguoidung');
        },
        ViewPhanPhoiThietBi: function () {
            Tracking.Core.Processor.OpenWindow(1, 'Quanly/PhanPhoiThietBi.aspx', 'quanly1', 'Phân phối danh sách thiết bị', 550, 500, true, false, false, false, true, false, true, 'icon-lichsunguoidung');
        },
        ViewThuHoiThietBi: function () {
            Tracking.Core.Processor.OpenWindow(1, 'Quanly/ThuHoiThietBi.aspx', 'quanly1', 'Thu hồi danh sách thiết bị', 550, 480, true, false, false, false, true, false, true, 'icon-lichsunguoidung');
        },
        ViewOptionDisplay: function () {
            $('#divOptionDisplay').css('display', 'block');
            Tracking.Core.Processor.OpenWindow(2, '', 'divOptionDisplay', 'Tùy chỉnh hiển thị', 200, 120, true, false, false, false, true, false, true, 'icon-setting');
            $('#divOptionDisplay').window('open');
            if (nDisplay == 1) {
                $("input[name=Display][value=Id]").attr('checked', 'checked');
            }
            else if (nDisplay == 2) {
                $("input[name=Display][value=PlateNumber]").attr('checked', 'checked');
            }
            else {
                $("input[name=Display][value=None]").attr('checked', 'checked');
            }
        },
        ViewReport: function (type, title) {
            typeReport = type;
            Tracking.Core.Processor.OpenWindow(1, 'Report/Report.aspx', 'quanly', title, 850, 500, true, false, false, true, true, false, true, 'icon-lichsunguoidung', 1);
        },
        NumUserOnline: function (data) {

            $('#numonline').html(data.d);
        },
        VehicleStatus: function (data) {
            $('#numbercarblue').html(data.CarBlue);
            $('#numbercarred').html(data.CarRed);
            $('#numbercaryellow').html(data.CarYellow);
            $('#numbercargrey').html(data.CarGrey);
        },

        SelectecMenu: function () {
            $('.MenuLeftTool li').click(function () {
                $('.MenuLeftTool li a').removeClass();
                $(this).children().addClass('selected');
            });
        },
        QuanLyDanhSachThietBi: function () {
            Tracking.Core.Processor.OpenWindow(1, 'QuanLy/DanhSachThietBi.aspx', 'quanly', 'Danh sách thiết bị', 850, 400, true, false, false, false, true, false, true, 'icon-devices');
        },
        DanhSachPhuongTien: function () {
            Tracking.Core.Processor.OpenWindow(1, 'QuanLy/DanhSachPhuongTien.aspx', 'quanly', 'Danh sách phương tiện', 850, 400, true, false, false, false, true, false, true, 'icon-danhsachphuongtien');
        },
        DanhSachTaiXe: function () {
            Tracking.Core.Processor.OpenWindow(1, 'QuanLy/DanhSachTaiXe.aspx', 'quanly', 'Danh sách tài xế', 750, 350, true, false, false, false, true, false, true, 'icon-danhsachtaixe');
        },
        Add_EditDanhSachTaiXe: function (type) {
            var title = '';
            $('#EditDanhSachTaiXe').css('display', 'block');
            if (type == 1) {
                Tracking.Core.Processor.OpenWindow(2, '', 'EditDanhSachTaiXe', 'Thêm mới tài xế', 490, 200, true, '', '', '', true, '', true, 'icon-add'); //Goi tao window truoc Tiep theo moi mo. 
                $('#txtMaTaiXe').val('');
                $('#txtMaTaiXe').attr('readonly', 'readonly');
                $('#txtMaTaiXe').css('background-color', '#EEEEEE');
                $('#txtTaiKhoanSoHuu').val('');
                $('#txtTaiKhoanSoHuu').css('background-color', '#EEEEEE');
                $('#txtMaTaiXe').attr('readonly', 'readonly');
                $('#txtTenTaiXe').val('');
                $('#txtSoGiayPhep').val('');
                $('#txtPhone').val('');
                title = 'Thêm mới tài xế';
                $('#hdEdit_Add').val('1');
            }
            if (type == 2) {

                var rowdata = $('#tblDanhSachTaiXe').datagrid('getSelected');
                if (rowdata == null || rowdata == 'undefined') {
                    $.messager.alert('Thông báo!', 'Vui lòng chọn dòng dữ liệu cần cập nhật!', 'info');
                    return;
                }
                else {
                    title = 'Cập nhật tài xế';
                    Tracking.Core.Processor.OpenWindow(2, '', 'EditDanhSachTaiXe', 'Cập nhật tài xế', 490, 200, true, '', '', '', true, '', true, 'icon-edit'); //Goi tao window truoc Tiep theo moi mo. 
                    $('#txtMaTaiXe').val(rowdata.DriverID);
                    $('#txtMaTaiXe').attr('readonly', 'readonly');
                    $('#txtMaTaiXe').css('background-color', '#EEEEEE');
                    $('#txtTaiKhoanSoHuu').val(rowdata.Licensor);
                    $('#txtTaiKhoanSoHuu').attr('readonly', 'readonly');
                    $('#txtTaiKhoanSoHuu').css('background-color', '#EEEEEE');
                    $('#txtTenTaiXe').val(rowdata.DriverName);
                    $('#txtSoGiayPhep').val(rowdata.DrivingLicence);
                    $('#txtPhone').val(rowdata.Phone);
                    $('#hdEdit_Add').val('2');
                }
            }

            $('#EditDanhSachTaiXe').dialog('open');
            $('#EditDanhSachTaiXe').dialog('setTitle', title);

        },

        Add_EditDanhSachPhuongTien: function (type) {
            var title = '';
            $('#EditDanhSachPhuongTien').css('display', 'block');
            if (type == 1) {
                Tracking.Core.Processor.OpenWindow(2, '', 'EditDanhSachPhuongTien', 'Thêm mới phương tiện', 505, 260, true, '', '', '', true, '', true, 'icon-add'); //Goi tao window truoc Tiep theo moi mo. 
                $('#txtMaXe').val('');
                $('#txtMaXe').attr('readonly', 'readonly');
                $('#txtMaXe').css('background-color', '#EEEEEE');
                $('#txtTaiKhoanSoHuu').val('');
                $('#txtTaiKhoanSoHuu').css('background-color', '#EEEEEE');
                $('#txtTaiKhoanSoHuu').attr('readonly', 'readonly');
                $('#txtBSXe').val('');

                $('#txtDungTichXang').val('');
                $('#txtDienTheDay').val('');
                $('#txtDienTheHet').val('');
                $('#txtVIN').val('');
                title = 'Thêm mới phương tiện';
                $('#hdEdit_Add').val('1');
            }
            if (type == 2) {

                var rowdata = $('#tbDanhSachPhuongTien').datagrid('getSelected');
                if (rowdata == null || rowdata == 'undefined') {
                    $.messager.alert('Thông báo!', 'Vui lòng chọn dòng dữ liệu cần cập nhật!', 'info');
                    return;
                }
                else {

                    title = 'Cập nhật phương tiện';
                    Tracking.Core.Processor.OpenWindow(2, '', 'EditDanhSachPhuongTien', 'Cập nhật phương tiện', 505, 260, true, '', '', '', true, '', true, 'icon-edit'); //Goi tao window truoc Tiep theo moi mo. 
                    $('#txtMaXe').val(rowdata.MaXe);
                    $('#txtMaXe').attr('readonly', 'readonly');
                    $('#txtMaXe').css('background-color', '#EEEEEE');
                    $('#txtTaiKhoanSoHuu').val(rowdata.NguoiCap);
                    $('#txtTaiKhoanSoHuu').css('background-color', '#EEEEEE');
                    $('#txtTaiKhoanSoHuu').attr('readonly', 'readonly');
                    $('#txtBSXe').val(rowdata.BienSoXe);

                    $('#txtDungTichXang').val(rowdata.DungTichBinhXang);
                    $('#txtDienTheDay').val(rowdata.DienKeDay);
                    $('#txtDienTheHet').val(rowdata.DienKeHet);
                    $('#txtVIN').val(rowdata.Vin);

                    $('#hdEdit_Add').val('2');
                }
            }

            $('#EditDanhSachPhuongTien').dialog('open');
            $('#EditDanhSachPhuongTien').dialog('setTitle', title);

        },
        UnSelectRecord: function (tb) {
            $('#' + tb).datagrid('unselectAll');
        },
        CollapseTab: function (id) {
            $('#main').layout('collapse', id);
            map.checkResize();
            setTimeout("$('.panel-tool .layout-button-up').bind('click',function(){setTimeout('map.checkResize()',1200);})", 1000);

        }

    },
    /* End interface*/
    /* Begin Business: Operation Add-Edit-Update-Delete, Tim kiem...(Muc Dich: thuc hien tat ca cac nghiep vu them xoa sua)*/
    Business: {
        /*Begin Quan ly nguoi dung */
        //Function tim kiem
        SearchUser: function (keysearch) {
            Tracking.Core.Business.DanhSachNguoiDung(keysearch);
        },

        /* End quan ly nguoi dung*/

        HistoryUser: function () {

            $(function () {
                $('#tbHistoryUser').datagrid({
                    method: 'get',
                    singleSelect: true,
                    url: 'ServiceTracking.asmx/HistoryUser',
                    pagination: true,
                    rownumbers: true,
                    nowrap: false,
                    fitColumns: true,
                    showPageList: false,
                    pageSize: 50,
                    queryParams: { 'fromday': fromdate, 'today': todate },
                    onLoadError: function () {
                        window.location.href = 'Login.aspx?ReturnUrl=Default.aspx';
                        // $.messager.alert('Thông báo!', 'Load dữ liệu bị lỗi!', 'error');
                        return;
                    },
                    onLoadSuccess: function () {


                    },
                    onClickRow: function (id, ob) {

                    }
                });
            });
        },
        NhapThongTin: function (type, rowindex) {

            var id = $('#ID').val();
            var fullname = $('#txtfullname').val();
            var sortname = $('#txtsortname').val();
            var phone = $('#txtphone').val();
            var address = $('#txtAddress').val();
            var coordiantes = $('#txtCoordiantes').val();
            var param = "{ param:\"{id:'" + id + "',fullname:'" + fullname + "',sortname:'" + sortname + "',phone:'" + phone + "',address:'" + address + "',coordiantes: '" + coordiantes + "', type:'" + type + "'}\"}"; //,  fullname, sortname: sortname, phone: phone, address: address, coordiantes: coordiantes, type: type 
            //Goi len server de cap nhat lai du lieu
            Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/NhapThongTin', param, Tracking.Core.Business.CallBackThongTin, 'POST', 'true', 'json', 'application/json; charset=utf-8');
            //Cap nhat vao gridview
            if (type == 1) {
                $('#tbNhapThongTin').datagrid('appendRow', {
                    ID: id,
                    FullName: fullname,
                    SortName: sortname,
                    Phone: phone,
                    Address: address,
                    Coordinate: coordiantes
                });
            }
            else {

                $('#tbNhapThongTin').datagrid('updateRow', {
                    index: rowindex,
                    row: {
                        FullName: fullname,
                        SortName: sortname,
                        Phone: phone,
                        Address: address,
                        Coordinate: coordiantes
                    }
                });
            }
        },

        DeleteNhapThongTin: function () {
            var rowdata = $('#tbNhapThongTin').datagrid('getSelected');
            if (rowdata == null) {
                $.messager.alert('Thông báo!', 'Vui lòng chọn dòng cần xóa!', 'info');
                return;
            }
            else {

                $.messager.confirm('Thông báo!', 'Bạn chắc chắn muốn xóa dòng dữ liệu này không?', function (r) {
                    if (r) {
                        //Call len server
                        Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/DeleteNhapThongTin', '{id:\"' + rowdata.ID + '\"}', '', 'POST', 'true', 'json', 'application/json; charset=utf-8');
                        //Cập nhật lại lưới
                        var index = $('#tbNhapThongTin').datagrid('getRowIndex', rowdata);
                        $('#tbNhapThongTin').datagrid('deleteRow', index);
                    }
                });

            }
        },

        UpdateNhapThongTin: function (datarow, rowindex) {
            if (flagUpdateNhapThongTin) {
                Tracking.Core.Processor.OpenWindow(1, 'PropertyNhapThongTin.aspx', 'quanly', 'Nhập thông tin', 320, 270, false, false, false, false, true, false, true);
                setTimeout(function () {
                    $('#id').val(datarow.ID);
                    $('#txtfullname').val(datarow.FullName);
                    $('#txtsortname').val(datarow.SortName);
                    $('#txtphone').val(datarow.Phone);
                    $('#txtAddress').val(datarow.Address);
                    $('#txtCoordiantes').val(datarow.Coordinate);

                    $('#btnNhapThongTin').die();
                    $('#btnNhapThongTin').html('<span class="l-btn-left"><span class="l-btn-text icon-ok" style="padding-left: 20px;">Cập nhật</span></span>')
                    $('#btnNhapThongTin').bind('click', function () { Tracking.Core.Business.NhapThongTin(2, rowindex) });

                }, 250);
            }
        },

        DanhSachNguoiDung: function (keysearch) {
            $(function () {
                $('#ListUser').datagrid({
                    method: 'get',
                    singleSelect: true,
                    url: 'service/Function/DanhSachNguoiDung.ashx', //Goi len Server de get du lieu
                    pagination: true,
                    rownumbers: true,
                    nowrap: false,
                    fitColumns: true,
                    showPageList: false,
                    pageSize: 20,
                    queryParams: { keysearch: keysearch },
                    onLoadError: function () {
                        return;
                    },
                    onLoadSuccess: function () {


                    },
                    onDblClickRow: function (id, ob) {
                        Tracking.Core.Interface.Edit_AddUserForm(2);
                    }
                });
            });
        },
        //Truong hop them hay Update dieu goi ham nay thuc thi phan biet giua chung bang cờ flagAdd_EditNguoiDung
        ThemDanhSachNguoiDung: function () {

            var param = Tracking.Core.Business.GetDanhSachNguoiDung(flagAdd_EditNguoiDung);
            if (param == '') {
                return;
            }
            //cap nhat lai luoi
            // chuyen 1 chuoi param thanh kieu json
            var par = eval("(" + param + ")"); //ep kieu json lan 1: lop 1
            par = eval("(" + par.param + ")"); // ep kieu json lan 2: lop 2
            //flagAdd_EditNguoiDung = true: cap nhat
            /* phần cập nhạt lại lưới */
            /*if (flagAdd_EditNguoiDung) {
            var rowdata = $('#ListUser').datagrid('getSelected');
            var rowindex = $('#ListUser').datagrid('getRowIndex', rowdata);
            $('#ListUser').datagrid('updateRow', {
            index: rowindex,
            row: {
            Name: par.tentaikhoan,
            DisplayName: par.tenhienthi,
            Tel: par.dienthoai,
            Email: par.email,
            Active: Tracking.Core.Business.UpdateStatusDanhSachNguoiDung(par.kichhoat)
            }
            });
            }
            else { //flagAdd_EditNguoiDung = true: them moi

            $('#ListUser').datagrid('appendRow', {
            Name: par.tentaikhoan,
            DisplayName: par.tenhienthi,
            Tel: par.dienthoai,
            Email: par.email,
            Active: Tracking.Core.Business.UpdateStatusDanhSachNguoiDung(par.kichhoat)
            });

            }*/
            /* Kết thúc cập nhật lưới */
            Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/ThemDanhSachNguoiDung', param, Tracking.Core.Business.CallBackThongTin, 'POST', true, 'json', 'application/json; charset=utf-8');
            //reload lai Data from server
            $('#ListUser').datagrid('reload');
            Tracking.Core.Processor.CloseWindow(2, 'EditUser');
        },
        DeleteDanhSachNguoiDung: function () {
            var rowdata = $('#ListUser').datagrid('getSelected');
            if (rowdata == null) {
                $.messager.alert('Thông báo!', 'Vui lòng chọn dòng cần xóa!', 'info');
                return;
            }
            else {

                $.messager.confirm('Thông báo!', 'Bạn chắc chắn muốn xóa dòng dữ liệu này không?', function (r) {
                    if (r) {
                        //Call len server
                        Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/DeleteDanhSachNguoiDung', '{id:\"' + rowdata.ID + '\"}', Tracking.Core.Business.CallBackThongTin, 'POST', true, 'json', 'application/json; charset=utf-8');
                        $('#ListUser').datagrid('reload');
                        //Cập nhật lại lưới
                        //var index = $('#ListUser').datagrid('getRowIndex', rowdata);
                        //$('#ListUser').datagrid('deleteRow', index);
                    }
                });

            }

        },
        GetDanhSachNguoiDung: function (type) {

            var tentaikhoan = $('#txtTenTaiKhoan').val();
            if (tentaikhoan == '') {
                $('#txtTenTaiKhoan').focus();
                $.messager.alert('Thông báo!', 'Tài khoản không được trống!', 'info');
                return '';
            }
            var tenhienthi = $('#txtTenHienThi').val();
            if (tenhienthi == '') {
                $('#txtTenHienThi').focus();
                $.messager.alert('Thông báo!', 'Tên hiển thị không được trống!', 'info');
                return '';
            }
            var nguoicap = $('#txtNguoiCap').val();
            var dienthoai = $('#txtDienThoai').val();
            var password = $('#txtPassword').val();
            var email = $('#txtEmail').val();
            if (email == '') {
                $('#txtEmail').focus();
                $.messager.alert('Thông báo!', 'Email không được trống!', 'info');
                return '';
            }
            if (!Tracking.Core.Utility.IsEmail(email)) {
                $.messager.alert('Thông báo!', 'Email không hợp lệ!', 'info');
                return '';
            }
            var kichhoat = $('#chkKichHoat');
            kichhoat = kichhoat.is(':checked') ? true : false;
            var id = $('#hdIdNguoidung').val();
            var param = "{param:\"{tentaikhoan:'" + tentaikhoan + "',tenhienthi:'" + tenhienthi + "', nguoicap:'" + nguoicap + "', dienthoai:'" + dienthoai + "',password:'" + password + "', email:'" + email + "',kichhoat:'" + kichhoat + "',id:'" + id + "', type: '" + type + "' }\"}";
            return param;
        },

        UpdateStatusDanhSachNguoiDung: function (b) {
            var action = "";
            if (b == 'false') {
                action = '<input type=checkbox disabled=\"disabled\" />';
            }
            else {
                action = '<input type=checkbox checked=checked disabled=\"disabled\" />';
            }

            return action;
        },
        XoaMatKhauNguoiDung: function () {
            var id = $('#hdIdNguoidung').val();
            var passwordreset = "1";
            Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/XoaMatKhauNguoiDung', '{id:\"' + id + '\"}', Tracking.Core.Business.CallBackThongTin, 'POST', true, 'json', 'application/json; charset=utf-8');
        },
        ThongTinNguoiDung: function () {
            Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/GetThongTinNguoiDung', '', Tracking.Core.Business.ThongTinNguoiDungCallBack, 'POST', true, 'json', 'application/json; charset=utf-8');
        },
        ThongTinNguoiDungCallBack: function (data) {
            data = data.d;
            $('#txtTenTaiKhoan').val(data.Name);
            $('#txtDienThoai').val(data.ContactCellPhone);
            $('#txtTenHienThi').val(data.ContactFullName);
            $('#txtEmail').val(data.ContactEmail);
            $('#txtCreateDate').val(data.CreatedTime);
        },
        ChangePassWord: function () {
            var sPasswordOld = $('#txtPasswordOld').val();
            var sPasswordNew = $('#txtPasswordNew').val();
            var sConfirmPassWordNew = $('#txtConfirmPasswordNew').val();
            if (sPasswordNew != sConfirmPassWordNew) {
                $.messager.alert('Thông báo!', 'Mật khẩu xác nhận mới không khớp!', 'info');
                return;
            }
            var param = "{param:\"{PasswordOld:'" + sPasswordOld + "', PasswordNew:'" + sPasswordNew + "'}\"}"; ;
            Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/ChangePassWord', param, Tracking.Core.Business.CallBackThongTin, 'POST', true, 'json', 'application/json; charset=utf-8');
        },
        CapNhatThongTinNguoiDung: function () {
            var sDienThoai = $('#txtDienThoai').val();
            var sTenHienThi = $('#txtTenHienThi').val();
            var sEmail = $('#txtEmail').val();
            var sName = $('#txtTenTaiKhoan').val();

            if (sEmail == '' || Tracking.Core.Utility.IsEmail(sEmail) == false) {
                $.messager.alert('Thông báo!', 'Địa chỉ Email không hợp lệ!', 'info');
                return;
            }
            var param = "{param:\"{DienThoai:'" + sDienThoai + "', TenHienThi:'" + sTenHienThi + "',Email:'" + sEmail + "', Name:'" + sName + "' }\"}"; ;
            Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/CapNhatThongTingNguoiDung', param, Tracking.Core.Business.CallBackThongTin, 'POST', true, 'json', 'application/json; charset=utf-8');
        },
        XoaDanhSachVung: function () {

            //Cap nhat lai luoi
            var rowdata = $('#tbDanhSachVung').datagrid('getSelected');
            if (rowdata == null) {
                $.messager.alert('Thông báo!', 'Vui lòng chọn dòng cần xóa!', 'info');

            }
            else {
                var index = $('#tbDanhSachVung').datagrid('getRowIndex', rowdata);
                var id = 1; //rowdata.ID;
                $('#tbDanhSachVung').datagrid('deleteRow', index);
                //Call Server
                Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/XoaDanhSachVung', '{id:\"' + id + '\"}', Tracking.Core.Business.CallBackThongTin, 'POST', true, 'json', 'application/json; charset=utf-8');
            }

        },
        PhanPhoiThietBi: function () {
            $('#tbPhanPhoiThietBi').datagrid({
                method: 'get',
                singleSelect: true,
                url: 'service/Function/PhanPhoiThietBi.ashx',
                pagination: true,
                rownumbers: true,
                nowrap: false,
                fitColumns: true,
                showPageList: true,
                pageSize: 50,
                pageList: [50, 100, 150],
                selectOnCheck: false,
                checkOnSelect: false,
                onLoadError: function () {
                    return;
                },
                onLoadSuccess: function () {

                },
                onDblClickRow: function (id, ob) {
                }
            });

        },
        ThemPhanPhoiThietBi: function () {
            var userid = $('#cbNguoiDung').combobox('getValue');
            if (userid == '' || userid == undefined) {
                $.messager.alert('Thông báo!', 'Bạn chưa chọn người dùng con để phân phối!', 'info');
                $('#cbNguoiDung').focus();
                return;
            }
            var arrTrk = new Array();
            var ck = $('#tbPhanPhoiThietBi').datagrid('getChecked');
            if (ck.length > 0) {
                for (var i = 0; i < ck.length; i++) {
                    arrTrk[arrTrk.length] = ck[i].TrackID;
                }
                var param = "{param:\"{userid:'" + userid + "', arrTrk:'" + arrTrk + "' }\"}"; ;
                Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/PhanPhoiThietBi', param, Tracking.Core.Business.CallBackThongTin, 'POST', true, 'json', 'application/json; charset=utf-8');
                $('#tbPhanPhoiThietBi').datagrid('reload');
            }
            else {
                $.messager.alert('Thông báo!', 'Bạn chưa chọn thiết bị để phân phối!', 'info');
                return;
            }

        },
        ThuHoiThietBi: function (userid) {
            $('#tbThuHoiThietBi').datagrid({
                method: 'get',
                singleSelect: true,
                url: 'service/Function/ThuHoiThietBi.ashx',
                pagination: true,
                rownumbers: true,
                nowrap: false,
                fitColumns: true,
                showPageList: false,
                pageSize: 50,
                pageList: [50, 100, 150],
                selectOnCheck: false,
                checkOnSelect: false,
                queryParams: { userid: userid },
                onLoadError: function () {
                    return;
                },
                onLoadSuccess: function () {

                },
                onDblClickRow: function (id, ob) {
                }
            });

        },
        ThucHienThuHoiThietBi: function () {
            var arrTrk = new Array();
            var ck = $('#tbThuHoiThietBi').datagrid('getChecked');
            if (ck.length > 0) {
                for (var i = 0; i < ck.length; i++) {
                    arrTrk[arrTrk.length] = ck[i].TrackID;
                }
                var param = "{param:\"{arrTrk:'" + arrTrk + "' }\"}";
                Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/ThuHoiThietBi', param, Tracking.Core.Business.CallBackThongTin, 'POST', true, 'json', 'application/json; charset=utf-8');
                $('#tbThuHoiThietBi').datagrid('reload');
            }
        },
        TimThietBiTheoUser: function () {
            var iduser = $('#cbNguoiDung').combobox('getValue');
            Tracking.Core.Business.ThuHoiThietBi(iduser);
        },
        CallBackThongTin: function (data, icon) {
            icon = 'info';
            $.messager.alert('Thông báo!', data.d, icon);
        },
        LoadGridData: function (url, div) {
            var fromdate = $('[name=fromdateReport]').val();
            var todate = $('[name=todateReport]').val();
            var pData = "{fromdate:'" + fromdate + "', todate:'" + todate + "', typereport:'" + typeReport + "'}";
            $('#divbtnReport').css('display', 'block');

            switch (typeReport) {
                case 1:
                    {
                        delta = 40;
                        Tracking.Core.Ajax.LoadDataToGrid(url, div, pData);
                        break;
                    }
                case 2:
                    {
                        delta = 40;
                        Tracking.Core.Ajax.LoadDataToGrid(url, div, pData);
                        break;
                    }
                case 3:
                    {
                        delta = 40;
                        Tracking.Core.Ajax.LoadDataToGrid(url, div, pData);
                        break;
                    }
                case 4:
                    {
                        delta = 40;
                        Tracking.Core.Ajax.LoadDataToGrid(url, div, pData);
                        break;
                    }
                case 5:
                    {
                        delta = 40;
                        Tracking.Core.Ajax.LoadDataToGrid(url, div, pData);
                        break;
                    }
                case 6:
                    {
                        delta = 40;
                        Tracking.Core.Ajax.LoadDataToGrid(url, div, pData);
                        break;
                    }
                case 7:
                    {
                        delta = 40;
                        Tracking.Core.Ajax.LoadDataToGrid(url, div, pData);
                        break;
                    }
                case 8:
                    {
                        delta = 40;
                        Tracking.Core.Ajax.LoadDataToGrid(url, div, pData);
                        break;
                    }
            }
        },
        ExportLotrinh: function () {
            var param = '';
            var fdate = $('[name=fromdatelotrinh]').val();
            var tdate = $('[name=todatelotrinh]').val();
            var selectSearch = $('#selectSearch').combobox('getValue');
            var SelectTypeSearch = $('#SelectTypeSearch').combobox('getValue');
            param = "{fromday:'" + fdate + "', today:'" + tdate + "',selectSearch:'" + selectSearch + "',SelectTypeSearch:'" + SelectTypeSearch + "' }";
            window.location.href = 'Report/ReportLoTrinh.ashx?param=' + param;
        },
        XemLaiLoTrinh: function () {
            //Parameter
            $('#tbXemlailotrinh').datagrid('loadData', { "total": 0, "rows": [] });
            //$('#tbXemlailotrinh').datagrid({ pageNumber: 1 });
            var fdate = $('[name=fromdatelotrinh]').val();
            var tdate = $('[name=todatelotrinh]').val();
            var selectSearch = $('#selectSearch').combobox('getText');
            var SelectTypeSearch = $('#SelectTypeSearch').combobox('getValue');
            Tracking.Core.Business.GetMarkerRouter();
            if (selectSearch != "") {
                Tracking.Core.Init.XemLoTrinh(fdate, tdate, selectSearch, '', '');
            }

        },

        SelectRecordsXemLaiLoTrinh: function (numberrecord) {
            var nloop = parseInt((numberrecord / 50), 10);
            var i = 0;
            setInterval(function () {
                if (i > nloop) {
                    return;
                }
                else {
                    $('#tbXemlailotrinh').datagrid('selectRow', (i * 50) + 49);
                }
                i++;
            }, 300);

        },
        GetMarkerRouter: function () {
            var param = '';
            var level = map.getLevel();
            var bound = map.getDirectionBounds();

            var param = "param={level:'" + level + "',left:'" + parseFloat(bound.getNorthWest().lng()) + "',bottom:'" + parseFloat(bound.getNorthWest().lat()) + "',right:'" + parseFloat(bound.getSouthEast().lng()) + "',top:'" + parseFloat(bound.getSouthEast().lat()) + "' }";
            Tracking.Core.Ajax.CallServer('Service/GetMarkerRouter.ashx', param, Tracking.Core.Processor.GetMarkerRouterCallback, 'GET', true, 'json'); //, 'application/json; charset=utf-8'
        },
        QuanLyDanhSachThietBi: function () {
            $(function () {
                $('#tblDanhSachThietBi').datagrid({
                    method: 'get',
                    singleSelect: true,
                    url: 'service/Function/DanhSachThietBi.ashx', //Goi len Server de get du lieu
                    pagination: true,
                    rownumbers: true,
                    nowrap: false,
                    fitColumns: true,
                    showPageList: false,
                    pageSize: 20,
                    queryParams: {},
                    onLoadError: function () {
                        return;
                    },
                    onLoadSuccess: function () {


                    },
                    onDblClickRow: function (id, ob) {

                    }
                });
            });

            var pager = $('#tblDanhSachThietBi').datagrid('getPager'); // get the pager of datagrid
            pager.pagination({
                buttons: [{
                    iconCls: 'icon-remove',
                    handler: function () {

                        var rowdata = $('#tblDanhSachThietBi').datagrid('getSelected');
                        if (rowdata == null) {
                            $.messager.alert('Thông báo!', 'Vui lòng chọn dòng cần xóa!', 'info');
                            return;
                        }
                        else {
                            var index = $('#tblDanhSachThietBi').datagrid('getRowIndex', rowdata);
                            var id = rowdata.DeviceID;
                            $('#tblDanhSachThietBi').datagrid('deleteRow', index);
                            //Call Server
                            Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/DeleteDanhSachThietBi', '{id:\"' + id + '\"}', Tracking.Core.Business.CallBackThongTin, 'POST', true, 'json', 'application/json; charset=utf-8');

                        }
                    }
                },
                      {
                          iconCls: 'icon-edit',
                          handler: function () {
                              var rowdata = $('#tblDanhSachThietBi').datagrid('getSelected');
                              if (rowdata == null) {
                                  $.messager.alert('Thông báo!', 'Vui lòng chọn dòng cần cập nhật!', 'info');
                                  return;
                              }
                              else {
                                  var index = $('#tblDanhSachThietBi').datagrid('getRowIndex', rowdata);
                                  alert(rowdata.DeviceID);
                              }
                          }
                      }]
            });
        },
        DanhSachTaiXe: function () {
            $(function () {
                $('#tblDanhSachTaiXe').datagrid({
                    method: 'get',
                    singleSelect: true,
                    url: 'service/Function/DanhSachTaiXe.ashx', //Goi len Server de get du lieu
                    pagination: false,
                    rownumbers: true,
                    nowrap: false,
                    fitColumns: true,
                    showPageList: false,
                    pageSize: 20,
                    queryParams: {},
                    onLoadError: function () {
                        return;
                    },
                    onLoadSuccess: function () {


                    },
                    onDblClickRow: function (id, ob) {

                    }
                });
            });


        },

        Add_Edit_DanhSachTaiXe: function () {
            var type = $('#hdEdit_Add').val();
            var obj = Tracking.Core.Business.GetDanhSachTaiXe();
            var param = "{param:\"{MTX:'" + obj.MaTaiXe + "', TKSH:'" + obj.TaiKhoanSoHuu + "', TTX: '" + obj.TenTaiXe + "', SGP:'" + obj.SoGiayPhep + "', Phone:'" + obj.Phone + "',type:'" + type + "'}\"}";
            if (type == 1) {

                $('#tblDanhSachTaiXe').datagrid('appendRow', {
                    DriverID: obj.MaTaiXe,
                    Licensor: obj.TaiKhoanSoHuu,
                    DriverName: obj.TenTaiXe,
                    Phone: obj.Phone,
                    DrivingLicence: obj.SoGiayPhep
                });
            }
            else {
                var rowdata = $('#tblDanhSachTaiXe').datagrid('getSelected');
                var rowindex = $('#tblDanhSachTaiXe').datagrid('getRowIndex', rowdata);
                $('#tblDanhSachTaiXe').datagrid('updateRow', {
                    index: rowindex,
                    row: {
                        DriverID: obj.MaTaiXe,
                        Licensor: obj.TaiKhoanSoHuu,
                        DriverName: obj.TenTaiXe,
                        Phone: obj.Phone,
                        DrivingLicence: obj.SoGiayPhep
                    }
                });
            };
            Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/Add_Edit_DanhSachTaiXe', param, Tracking.Core.Business.CallBackThongTin, 'POST', true, 'json', 'application/json; charset=utf-8');
        },
        DeleteDanhSachTaiXe: function () {
            //Cap nhat lai luoi
            var rowdata = $('#tblDanhSachTaiXe').datagrid('getSelected');
            if (rowdata == null) {
                $.messager.alert('Thông báo!', 'Vui lòng chọn dòng cần xóa!', 'info');

            }
            else {
                var index = $('#tblDanhSachTaiXe').datagrid('getRowIndex', rowdata);
                var id = rowdata.DriverID;
                $('#tblDanhSachTaiXe').datagrid('deleteRow', index);
                //Call Server
                Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/DeleteDanhSachTaiXe', '{id:\"' + id + '\"}', Tracking.Core.Business.CallBackThongTin, 'POST', true, 'json', 'application/json; charset=utf-8');
            }
        },
        GetDanhSachTaiXe: function () {
            var obj = new Object();
            obj.MaTaiXe = $('#txtMaTaiXe').val();
            obj.TaiKhoanSoHuu = $('#txtTaiKhoanSoHuu').val();
            obj.TenTaiXe = $('#txtTenTaiXe').val();
            obj.SoGiayPhep = $('#txtSoGiayPhep').val();
            obj.Phone = $('#txtPhone').val();
            return obj;
        },

        DanhSachPhuongTien: function () {
            $(function () {
                $('#tbDanhSachPhuongTien').datagrid({
                    method: 'get',
                    singleSelect: true,
                    url: 'service/Function/DanhSachPhuongTien.ashx', //Goi len Server de get du lieu
                    pagination: true,
                    rownumbers: true,
                    nowrap: false,
                    fitColumns: true,
                    showPageList: true,
                    pageSize: 20,
                    queryParams: {},
                    onLoadError: function () {
                        return;
                    },
                    onLoadSuccess: function () {


                    },
                    onDblClickRow: function (id, ob) {

                    }
                });
            });

            var pager = $('#tbDanhSachPhuongTien').datagrid('getPager'); // get the pager of datagrid
            pager.pagination({
                buttons: [
                {
                    iconCls: 'icon-add',
                    handler: function () {
                        Tracking.Core.Interface.Add_EditDanhSachPhuongTien(1);
                    }
                },
                {
                    iconCls: 'icon-remove',
                    handler: function () {

                        var rowdata = $('#tbDanhSachPhuongTien').datagrid('getSelected');
                        if (rowdata == null) {
                            $.messager.alert('Thông báo!', 'Vui lòng chọn dòng cần xóa!', 'info');
                            return;
                        }
                        else {
                            var index = $('#tbDanhSachPhuongTien').datagrid('getRowIndex', rowdata);
                            var id = rowdata.DeviceID;
                            $('#tbDanhSachPhuongTien').datagrid('deleteRow', index);
                            //Call Server
                            Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/DeleteDanhSachPhuongTien', '{id:\"' + id + '\"}', Tracking.Core.Business.CallBackThongTin, 'POST', true, 'json', 'application/json; charset=utf-8');

                        }
                    }
                },
                      {
                          iconCls: 'icon-edit',
                          handler: function () {
                              //                              var rowdata = $('#tbDanhSachPhuongTien').datagrid('getSelected');
                              //                              if (rowdata == null) {
                              //                                  $.messager.alert('Thông báo!', 'Vui lòng chọn dòng cần cập nhật!', 'info');
                              //                                  return;
                              //                              }
                              //                              else {
                              //                                  var index = $('#tbDanhSachPhuongTien').datagrid('getRowIndex', rowdata);
                              Tracking.Core.Interface.Add_EditDanhSachPhuongTien(2);
                              //}
                          }
                      }
                      ]
            });
        },
        Add_EditDanhSachPhuongTien: function () {

            var type = $('#hdEdit_Add').val();
            var obj = Tracking.Core.Business.GetDanhSachPhuongTien();
            var param = "{param:\"{MX:'" + obj.MaXe + "', NguoiCap:'" + obj.TaiKhoanSoHuu + "', TaiXe: '" + obj.TaiXe + "', LoaiPhuongTien:'" + obj.LoaiPT + "', BienSoXe:'" + obj.BSXe + "',DungTichBinhXang:'" + obj.DungTichXang + "', DienKeDay:'" + obj.DienTheDay + "', DienKeHet:'" + obj.DienTheHet + "',Vin:'" + obj.VIN + "', type:'" + type + "'}\"}";
            if (type == 1) {

                $('#tbDanhSachPhuongTien').datagrid('appendRow', {
                    MX: obj.MX,
                    NguoiCap: obj.TaiKhoanSoHuu,
                    TaiXe: $('#SelectTaiXe').combobox('getText'),
                    LoaiPhuongTien: $('#SelectLoaiPT').combobox('getText'), //Can viet ham tra ve PT (truyen vao ma PT)
                    BienSoXe: obj.BSXe,
                    DungTichBinhXang: obj.DungTichXang,
                    DienKeDay: obj.DienTheDay,
                    DienKeHet: obj.DienTheHet,
                    Vin: obj.VIN
                });
            }
            else {
                var rowdata = $('#tbDanhSachPhuongTien').datagrid('getSelected');
                var rowindex = $('#tbDanhSachPhuongTien').datagrid('getRowIndex', rowdata);
                $('#tbDanhSachPhuongTien').datagrid('updateRow', {
                    index: rowindex,
                    row: {
                        MX: obj.MX,
                        NguoiCap: obj.TaiKhoanSoHuu,
                        TaiXe: $('#SelectTaiXe').combobox('getText'),
                        LoaiPhuongTien: $('#SelectLoaiPT').combobox('getText'), //Can viet ham tra ve PT (truyen vao ma PT)
                        BienSoXe: obj.BSXe,
                        DungTichBinhXang: obj.DungTichXang,
                        DienKeDay: obj.DienTheDay,
                        DienKeHet: obj.DienTheHet,
                        Vin: obj.VIN
                    }
                });
            };
            Tracking.Core.Ajax.CallServer('ServiceTracking.asmx/Add_Edit_DanhSachPhuongTien', param, Tracking.Core.Business.CallBackThongTin, 'POST', true, 'json', 'application/json; charset=utf-8');
        },

        GetDanhSachPhuongTien: function () {
            var obj = new Object();
            obj.MaXe = $('#txtMaXe').val();
            obj.TaiKhoanSoHuu = $('#txtTaiKhoanSoHuu').val();
            obj.BSXe = $('#txtBSXe').val();
            obj.DungTichXang = $('#txtDungTichXang').val();
            obj.DienTheDay = $('#txtDienTheDay').val();
            obj.DienTheHet = $('#txtDienTheHet').val();
            obj.VIN = $('#txtVIN').val();
            obj.LoaiPT = $('#SelectLoaiPT').combobox('getValue');
            obj.TaiXe = $('#SelectTaiXe').combobox('getValue');
            return obj;
        },
        GetBoundRect: function () {
            var rectmap = map.getBounds();
            var _rect = new Object();
            _rect.dMinLat = Math.min(rectmap.getNorthWest().latitude, rectmap.getSouthEast().latitude);
            _rect.dMaxLat = Math.max(rectmap.getNorthWest().latitude, rectmap.getSouthEast().latitude);
            _rect.dMinLng = Math.min(rectmap.getNorthWest().longitude, rectmap.getSouthEast().longitude);
            _rect.dMaxLng = Math.max(rectmap.getNorthWest().longitude, rectmap.getSouthEast().longitude);
            rectmap = null;
            return _rect;
        },
        BinDataToGridXemLaiLoTrinh: function (data) {

            if (data.rows.length > 0) {
                var rows = [];
                for (var i = 0; i < data.rows.length; i++) {
                    rows.push({
                        ID: data.rows[i].ID
                    });

                }
                $('#tbXemlailotrinh').datagrid('loadData', rows);
            }
        },
        SearchDevice: function () {
            var page = $('#south .pagination-num').val();
            $('#tbDanhSachThietBi').datagrid('loadData', { "total": 0, "rows": [] });
            if (parseInt(page, 10) > 1) {
                $('#tbDanhSachThietBi').datagrid({ pageNumber: 1 });
            }

            var keysearch = $('#txtSearchDevice').val();
            Tracking.Core.Init.LoadDataToGrid(keysearch);
            fSearchDevice = true;
        },
        DisplayResultSearch: function (total, keysearch) {
            if (keysearch != '') {
                var arrResult = new Array();
                arrResult[arrResult.length] = "Đang hiển thị: ";
                arrResult[arrResult.length] = "<b>";
                arrResult[arrResult.length] = total;
                arrResult[arrResult.length] = "</b>";
                arrResult[arrResult.length] = " kết quả";
                arrResult[arrResult.length] = " với từ khóa tìm kiếm: ";
                arrResult[arrResult.length] = "<b>";
                arrResult[arrResult.length] = keysearch;
                arrResult[arrResult.length] = "</b>";
                arrResult[arrResult.length] = "<img alt='Xóa kết quả tìm kiếm' src='Styles/jqueryEasy/icons/cancel.png' onclick='Tracking.Core.Business.DeleteResultSearchDevice();' style='padding:0px 0px 0px 10px; cursor:pointer;' width='12px' height='12px' />";
                $('#resultSearch').html(arrResult.join(''));
            }
            fSearchDevice = false;
        },
        DeleteResultSearchDevice: function () {
            Tracking.Core.Init.LoadDataToGrid('');
            $('#resultSearch').html('');
            $('#txtSearchDevice').val('');
        }

    },
    //End Business
    Browser: {
        setCookie: function (c_name, value, exdays) {
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + exdays);
            var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
            document.cookie = c_name + "=" + c_value;
        },
        getCookie: function (c_name) {
            var i, x, y, ARRcookies = document.cookie.split(";");
            for (i = 0; i < ARRcookies.length; i++) {
                x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
                y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
                x = x.replace(/^\s+|\s+$/g, "");
                if (x == c_name) {
                    return unescape(y);
                }
            }
        }
    },
    Ajax: {
        CallServer: function (pUrl, pData, pFuncNameSuccess, pType, pAsync, pdataType, pcontenType) {
            pType = pType;
            pAsync = pAsync;

            $.ajax({
                url: pUrl,
                async: pAsync,
                cache: false,
                type: pType,
                data: pData,
                contentType: pcontenType,
                dataType: pdataType,
                success: pFuncNameSuccess,
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                    //$.messager.alert('Thông báo!', 'Load thiết bị bị lỗi!', 'error');
                    Tracking.Core.Processor.ClearTimeOut();
                    //window.location.href = 'Login.aspx?ReturnUrl=Default.aspx';
                    return;
                }
            });
        },
        LoadDataToGrid: function (url, div, pData) {

            $(document).ready(function () {
                $.post(url + '?para=' + pData,
            function (data) {
                $("div#" + div).empty().html('<img src="Images/5.gif"/>');
                $("div#" + div).html(data.replace('name="__VIEWSTATE" id="__VIEWSTATE"', 'id="cuibap" '));
                Tracking.Core.Processor.ResizeWindow('quanly', div, delta);

            });
            });


        }

    },
    Utility:
    {
        GetLength: function (latlngs) {
            if (this.isDirectionObj) return;
            var i, lineLength = 0;
            var dbTheta, dbDist, dbDistInRad, dbThetaInRad;
            var dbLat1InRad, dbLong1InRad, dbLat2InRad, dbLong2InRad;
            for (i = 0; i < latlngs.length - 1; i++) {
                dbLat1InRad = latlngs[i].latitude * (Math.PI / 180.0);
                dbLong1InRad = latlngs[i].longitude * (Math.PI / 180.0);
                dbLat2InRad = latlngs[i + 1].latitude * (Math.PI / 180.0);
                dbLong2InRad = latlngs[i + 1].longitude * (Math.PI / 180.0);

                dbTheta = latlngs[i].longitude - latlngs[i + 1].longitude;
                dbThetaInRad = dbTheta * (Math.PI / 180.0);

                dbDistInRad = Math.sin(dbLat1InRad) * Math.sin(dbLat2InRad) +
			    Math.cos(dbLat1InRad) * Math.cos(dbLat2InRad) * Math.cos(dbThetaInRad);

                dbDistInRad = Math.acos(dbDistInRad);
                dbDist = dbDistInRad * 180.0 / Math.PI;
                dbDist = dbDist * 60.0 * 1.1515;
                dbDist = dbDist * 1.609344 * 1000;
                lineLength += dbDist;
            }
            return lineLength;
        },
        FormatDistant: function (totalLng) {
            if (totalLng < 1000) {
                totalLng += "";
                if (totalLng.indexOf('.') < totalLng.length - 2)
                    totalLng = totalLng.substring(0, totalLng.indexOf('.') + 2);
                totalLng = totalLng + " m";
            }
            else {
                totalLng /= 1000;
                totalLng += "";
                if (totalLng.indexOf('.') < totalLng.length - 2)
                    totalLng = totalLng.substring(0, totalLng.indexOf('.') + 2);
                totalLng = totalLng + " km";
            }
            return totalLng;
        },
        IsEmail: function (email) {
            var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            return regex.test(email);
        }
    }
}
